﻿using UnityEngine;
using UnityEditor;

namespace CGF
{
    public class FindMissingScripts
    {

        static int missing_count = 0;

        [UnityEditor.MenuItem("GameObject/CGFramework/查找 Missing Scripts", priority = -2000)]
        static void Execute()
        {
            GameObject[] gos = Selection.gameObjects;
            if (gos.Length == 0)
            {
                EditorUtility.DisplayDialog("提示", "请选择一个Prefab", "确定");
                return;
            }
            missing_count = 0;
            foreach (GameObject go in gos)
            {
                FindInGo(go);
            }
            if (missing_count > 0)
            {
                Debug.LogError($"共找到{missing_count}个脚本丢失的节点");
            }
            else
            {
                Debug.Log("没有找到脚本丢失的节点");
            }
        }

        static void FindInGo(GameObject go)
        {
            Component[] components = go.GetComponents<Component>();
            for (int i = 0; i < components.Length; i++)
            {
                if (components[i] == null)
                {
                    missing_count++;
                    string s = go.name;
                    Transform t = go.transform;
                    while (t.parent != null)
                    {
                        s = t.parent.name + "/" + s;
                        t = t.parent;
                    }
                    Debug.LogError($"发现脚本丢失: {s}");
                }
            }
            foreach (Transform childT in go.transform)
            {
                FindInGo(childT.gameObject);
            }
        }
    }
}